<template>
  <div class="scientific-research-container">
    <div class="scientific-research-header">
      <div class="header-actions">
        <el-button type="primary" plain size="small" @click="goBack">
          <el-icon><Back /></el-icon> 返回首页
        </el-button>
      </div>
      <h1>科学研究</h1>
      <p>预约参观自然保护区，开展科学研究活动</p>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧预约和注意事项 -->
      <el-col :span="16">
        <!-- 预约参观 -->
        <el-card class="reservation-card">
          <template #header>
            <div class="card-header">
              <span>预约参观</span>
              <el-tag type="success" effect="dark">在线预约</el-tag>
            </div>
          </template>

          <el-form :model="reservationForm" :rules="reservationRules" ref="reservationFormRef" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="研究机构" prop="institution">
                  <el-input v-model="reservationForm.institution" placeholder="请输入研究机构名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="reservationForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="reservationForm.phone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="reservationForm.email" placeholder="请输入邮箱地址"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="参观日期" prop="visitDate">
                  <el-date-picker
                    v-model="reservationForm.visitDate"
                    type="date"
                    placeholder="选择参观日期"
                    :disabled-date="disabledDate"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="参观时间" prop="visitTime">
                  <el-time-picker
                    v-model="reservationForm.visitTime"
                    placeholder="选择参观时间"
                    format="HH:mm"
                    value-format="HH:mm"
                    style="width: 100%"
                  ></el-time-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="参观人数" prop="visitorCount">
              <el-input-number v-model="reservationForm.visitorCount" :min="1" :max="50" style="width: 200px"></el-input-number>
              <span style="margin-left: 10px; color: #909399;">人</span>
            </el-form-item>

            <!-- 新增保护区选择 -->
            <el-form-item label="预约保护区" prop="protectedArea">
              <el-select v-model="reservationForm.protectedArea" placeholder="请选择要预约的保护区" style="width: 100%" @change="handleProtectedAreaChange">
                <el-option label="胶南灵山岛保护区" value="erdihu"></el-option>
                <el-option label="大公岛保护区" value="yunmen"></el-option>
                <el-option label="大泽山保护区" value="bailang"></el-option>
                <el-option label="崂山保护区" value="xiashan"></el-option>
                <el-option label="胶州艾山保护区" value="binhai"></el-option>
                <el-option label="马山保护区" value="mihe"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="研究目的" prop="researchPurpose">
              <el-select v-model="reservationForm.researchPurpose" placeholder="请选择研究目的" style="width: 100%">
                <el-option label="生物多样性调查" value="biodiversity"></el-option>
                <el-option label="生态环境监测" value="environmental"></el-option>
                <el-option label="植物学研究" value="botany"></el-option>
                <el-option label="动物学研究" value="zoology"></el-option>
                <el-option label="地质学研究" value="geology"></el-option>
                <el-option label="气候学研究" value="climate"></el-option>
                <el-option label="其他" value="other"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="研究详情" prop="researchDetails">
              <el-input
                v-model="reservationForm.researchDetails"
                type="textarea"
                :rows="4"
                placeholder="请详细描述研究内容、方法和预期成果"
              ></el-input>
            </el-form-item>

            <el-form-item label="特殊需求">
              <el-input
                v-model="reservationForm.specialRequirements"
                type="textarea"
                :rows="3"
                placeholder="如需要特殊设备、向导服务等，请在此说明"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitReservation" :loading="submitting">
                <el-icon><Check /></el-icon> 提交预约
              </el-button>
              <el-button @click="resetForm">
                <el-icon><Refresh /></el-icon> 重置表单
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 参观注意事项 -->
        <el-card class="notice-card">
          <template #header>
            <div class="card-header">
              <span>参观注意事项</span>
              <el-tag type="warning" effect="dark">重要提醒</el-tag>
            </div>
          </template>

          <el-collapse v-model="activeNotices">
            <el-collapse-item title="预约须知" name="reservation">
              <ul class="notice-list">
                <li>请提前3-7个工作日进行预约，以便我们安排专业向导</li>
                <li>预约成功后，我们将在24小时内电话确认具体安排</li>
                <li>如需变更或取消预约，请提前48小时联系我们</li>
                <li>团体参观（10人以上）需要提前一周预约</li>
              </ul>
            </el-collapse-item>

            <el-collapse-item title="安全规定" name="safety">
              <ul class="notice-list">
                <li>进入保护区必须穿着长袖衣物和长裤，建议穿防滑鞋</li>
                <li>严禁携带火种，禁止吸烟</li>
                <li>不得离开指定路线，必须在向导陪同下活动</li>
                <li>遇到野生动物时保持安静，不得惊扰或投喂</li>
                <li>如有心脏病、高血压等疾病，请提前告知</li>
              </ul>
            </el-collapse-item>

            <el-collapse-item title="研究规范" name="research">
              <ul class="notice-list">
                <li>采集标本需要提前申请许可证，并严格按照规定进行</li>
                <li>禁止破坏植被和地质结构</li>
                <li>使用仪器设备需要提前报备，确保不影响生态环境</li>
                <li>研究数据和成果需要与保护区管理部门共享</li>
                <li>拍摄照片和视频需要遵守相关规定</li>
              </ul>
            </el-collapse-item>

            <el-collapse-item title="环保要求" name="environment">
              <ul class="notice-list">
                <li>严禁乱扔垃圾，所有废物必须带出保护区</li>
                <li>不得采摘植物或捕捉动物</li>
                <li>保持安静，避免大声喧哗</li>
                <li>爱护公共设施和标识牌</li>
                <li>遵循"只留下脚印，只带走照片"的原则</li>
              </ul>
            </el-collapse-item>
          </el-collapse>
        </el-card>

        <!-- 我的预约记录 / 管理员预约管理 -->
        <el-card class="my-reservations-card">
          <template #header>
            <div class="card-header">
              <span>{{ isAdmin ? '预约管理' : '我的预约记录' }}</span>
              <div>
                <el-button type="text" @click="refreshReservations">
                  <el-icon><Refresh /></el-icon> 刷新
                </el-button>
                <el-button v-if="isAdmin" type="primary" size="small" @click="showAdminPanel = true">
                  管理面板
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="displayReservations.length > 0">
            <el-table :data="displayReservations" style="width: 100%">
              <el-table-column prop="institution" label="研究机构" min-width="120" show-overflow-tooltip></el-table-column>
              <el-table-column prop="protectedAreaName" label="保护区" min-width="120" show-overflow-tooltip></el-table-column>
              <el-table-column prop="visitDate" label="参观日期" min-width="100"></el-table-column>
              <el-table-column prop="visitTime" label="参观时间" min-width="90"></el-table-column>
              <el-table-column prop="visitorCount" label="人数" min-width="60" align="center"></el-table-column>
              <el-table-column prop="researchPurpose" label="研究目的" min-width="110" show-overflow-tooltip>
                <template #default="scope">
                  {{ getResearchPurposeText(scope.row.researchPurpose) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="80" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusTagType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="150" align="center">
                <template #default="scope">
                  <el-button type="text" size="small" @click="viewReservationDetails(scope.row)">
                    查看详情
                  </el-button>
                  <!-- 普通用户只能取消自己的待确认预约 -->
                  <el-button
                    v-if="!isAdmin && scope.row.status === '待确认'"
                    type="text"
                    size="small"
                    @click="cancelReservation(scope.row)"
                  >
                    取消预约
                  </el-button>
                  <!-- 管理员可以确认或拒绝预约 -->
                  <template v-if="isAdmin">
                    <el-button
                      v-if="scope.row.status === '待确认'"
                      type="text"
                      size="small"
                      @click="confirmReservation(scope.row)"
                    >
                      确认
                    </el-button>
                    <el-button
                      v-if="scope.row.status === '待确认'"
                      type="text"
                      size="small"
                      @click="rejectReservation(scope.row)"
                    >
                      拒绝
                    </el-button>
                    <el-button
                      v-if="scope.row.status === '已确认'"
                      type="text"
                      size="small"
                      @click="completeReservation(scope.row)"
                    >
                      完成
                    </el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无预约记录"></el-empty>
        </el-card>
      </el-col>

      <!-- 右侧地图预览 -->
      <el-col :span="8">
        <!-- 地图预览 -->
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <span>保护区地图预览</span>
              <el-button type="text" @click="refreshMap">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div id="scientificMapView" class="map-container"></div>
        </el-card>

        <!-- 保护区选择 -->
        <el-card class="area-selection-card">
          <template #header>
            <div class="card-header">
              <span>选择研究区域</span>
            </div>
          </template>

          <div class="area-options">
            <el-radio-group v-model="selectedArea" @change="handleAreaChange">
              <el-radio label="erdihu">胶南灵山岛保护区</el-radio>
              <el-radio label="yunmen">大公岛保护区</el-radio>
              <el-radio label="bailang">大泽山保护区</el-radio>
              <el-radio label="xiashan">崂山保护区</el-radio>
              <el-radio label="binhai">胶州艾山保护区</el-radio>
              <el-radio label="mihe">马山保护区</el-radio>
            </el-radio-group>
          </div>
        </el-card>

        <!-- 联系信息 -->
        <el-card class="contact-card">
          <template #header>
            <div class="card-header">
              <span>联系我们</span>
            </div>
          </template>

          <div class="contact-info">
            <div class="contact-item">
              <el-icon><Phone /></el-icon>
              <span>预约热线：0532-8888-9999</span>
            </div>
            <div class="contact-item">
              <el-icon><Message /></el-icon>
              <span>邮箱：research@yuhuan.gov.cn</span>
            </div>
            <div class="contact-item">
              <el-icon><Clock /></el-icon>
              <span>工作时间：周一至周五 8:30-17:30</span>
            </div>
            <div class="contact-item">
              <el-icon><Location /></el-icon>
              <span>地址：山东省青岛市自然保护区管理中心</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 预约详情对话框 -->
  <el-dialog v-model="showReservationDialog" title="预约详情" width="600px">
    <div v-if="currentReservation" class="reservation-details">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="研究机构">{{ currentReservation.institution }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ currentReservation.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentReservation.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentReservation.email }}</el-descriptions-item>
        <el-descriptions-item label="参观日期">{{ currentReservation.visitDate }}</el-descriptions-item>
        <el-descriptions-item label="参观时间">{{ currentReservation.visitTime }}</el-descriptions-item>
        <el-descriptions-item label="参观人数">{{ currentReservation.visitorCount }}人</el-descriptions-item>
        <el-descriptions-item label="研究目的">{{ getResearchPurposeText(currentReservation.researchPurpose) }}</el-descriptions-item>
        <el-descriptions-item label="预约状态" :span="2">
          <el-tag :type="getStatusTagType(currentReservation.status)">{{ currentReservation.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="研究详情" :span="2">{{ currentReservation.researchDetails }}</el-descriptions-item>
        <el-descriptions-item label="特殊需求" :span="2">{{ currentReservation.specialRequirements || '无' }}</el-descriptions-item>
        <el-descriptions-item v-if="currentReservation.adminNote" label="管理员备注" :span="2">
          {{ currentReservation.adminNote }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </el-dialog>

  <!-- 管理员面板对话框 -->
  <el-dialog v-model="showAdminPanel" title="管理员面板" width="800px">
    <el-tabs v-model="activeAdminTab">
      <el-tab-pane label="预约统计" name="statistics">
        <div class="admin-statistics">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-number">{{ reservationStats.total }}</div>
                <div class="stat-label">总预约数</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-number pending">{{ reservationStats.pending }}</div>
                <div class="stat-label">待确认</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-number confirmed">{{ reservationStats.confirmed }}</div>
                <div class="stat-label">已确认</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-number completed">{{ reservationStats.completed }}</div>
                <div class="stat-label">已完成</div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="保护区统计" name="areas">
        <div class="area-statistics">
          <el-table :data="areaStats" style="width: 100%">
            <el-table-column prop="areaName" label="保护区名称" min-width="150"></el-table-column>
            <el-table-column prop="totalReservations" label="总预约数" min-width="100" align="center"></el-table-column>
            <el-table-column prop="pendingReservations" label="待确认" min-width="80" align="center"></el-table-column>
            <el-table-column prop="confirmedReservations" label="已确认" min-width="80" align="center"></el-table-column>
            <el-table-column prop="completedReservations" label="已完成" min-width="80" align="center"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <!-- 管理员操作确认对话框 -->
  <el-dialog v-model="showAdminActionDialog" :title="adminActionTitle" width="500px">
    <el-form :model="adminActionForm" label-width="80px">
      <el-form-item label="备注">
        <el-input
          v-model="adminActionForm.note"
          type="textarea"
          :rows="3"
          :placeholder="adminActionPlaceholder"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showAdminActionDialog = false">取消</el-button>
        <el-button type="primary" @click="executeAdminAction">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// 在文件顶部添加类型声明
declare global {
  interface Window {
    _tempReservations: ReservationRecord[]
  }
}

import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  Back,
  Check,
  Refresh,
  Phone,
  Message,
  Clock,
  Location
} from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import { gaodeLayer } from '@/utils/GaoDeBaseLayer'
import { useUserStore } from '@/stores/userStore'

// 类型定义
interface ReservationForm {
  institution: string
  contactPerson: string
  phone: string
  email: string
  visitDate: string | Date
  visitTime: string
  visitorCount: number
  researchPurpose: string
  researchDetails: string
  specialRequirements: string
  protectedArea: string
}

interface ReservationRecord extends ReservationForm {
  id: string
  status: '待确认' | '已确认' | '已完成' | '已取消' | '已拒绝'
  createTime: string
  visitDate: string
  protectedAreaName: string
  userId?: string
  adminNote?: string
}

interface AreaCenter {
  [key: string]: [number, number]
}

interface AdminActionForm {
  note: string
}

interface ReservationStats {
  total: number
  pending: number
  confirmed: number
  completed: number
}

interface AreaStats {
  areaName: string
  areaCode: string
  totalReservations: number
  pendingReservations: number
  confirmedReservations: number
  completedReservations: number
}

const router = useRouter()
const userStore = useUserStore()

// 地图和图层
let view: __esri.MapView
let featureLayer: __esri.FeatureLayer

// 状态变量
const loading = ref(false)
const submitting = ref(false)
const activeNotices = ref(['reservation'])
const selectedArea = ref('erdihu')
const showReservationDialog = ref(false)
const currentReservation = ref<ReservationRecord | null>(null)
const myReservations = ref<ReservationRecord[]>([])
const allReservations = ref<ReservationRecord[]>([])
const reservationFormRef = ref<FormInstance>()

// 管理员相关状态
const showAdminPanel = ref(false)
const activeAdminTab = ref('statistics')
const showAdminActionDialog = ref(false)
const adminActionForm = reactive<AdminActionForm>({
  note: ''
})
const adminActionTitle = ref('')
const adminActionPlaceholder = ref('')
const currentAdminAction = ref<{ type: string; reservation: ReservationRecord | null }>({
  type: '',
  reservation: null
})

// 计算属性
const isAdmin = computed(() => userStore.isAdmin)
const currentUserId = computed(() => userStore.currentUser?.id || '')

// 显示的预约记录（管理员看所有，普通用户只看自己的）
const displayReservations = computed(() => {
  if (isAdmin.value) {
    return allReservations.value
  } else {
    return myReservations.value.filter(r => r.userId === currentUserId.value)
  }
})

// 预约统计
const reservationStats = computed((): ReservationStats => {
  const stats = {
    total: allReservations.value.length,
    pending: allReservations.value.filter(r => r.status === '待确认').length,
    confirmed: allReservations.value.filter(r => r.status === '已确认').length,
    completed: allReservations.value.filter(r => r.status === '已完成').length
  }
  return stats
})

// 保护区统计
const areaStats = computed((): AreaStats[] => {
  const areaMap = {
    'erdihu': '胶南灵山岛保护区',
    'yunmen': '大公岛保护区',
    'bailang': '大泽山保护区',
    'xiashan': '崂山保护区',
    'binhai': '胶州艾山保护区',
    'mihe': '马山保护区'
  }

  return Object.entries(areaMap).map(([code, name]) => {
    const areaReservations = allReservations.value.filter(r => r.protectedArea === code)
    return {
      areaName: name,
      areaCode: code,
      totalReservations: areaReservations.length,
      pendingReservations: areaReservations.filter(r => r.status === '待确认').length,
      confirmedReservations: areaReservations.filter(r => r.status === '已确认').length,
      completedReservations: areaReservations.filter(r => r.status === '已完成').length
    }
  })
})

// 各个景区的中心坐标
const areaCenters: AreaCenter = {
  erdihu: [120.179558, 35.765965], // 胶南灵山岛坐标
  yunmen: [120.503415, 35.967122], // 大公岛坐标
  bailang: [120.022251, 37.00615], // 大泽山坐标
  xiashan: [120.605305, 36.198964], // 崂山坐标
  binhai: [119.93718, 36.121442], // 胶州艾山坐标
  mihe: [120.651138, 36.340289] // 马山坐标
}

// 预约表单
const reservationForm = reactive<ReservationForm>({
  institution: '',
  contactPerson: '',
  phone: '',
  email: '',
  visitDate: '',
  visitTime: '',
  visitorCount: 1,
  researchPurpose: '',
  researchDetails: '',
  specialRequirements: '',
  protectedArea: ''
})

// 表单验证规则
const reservationRules = {
  institution: [
    { required: true, message: '请输入研究机构名称', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  visitDate: [
    { required: true, message: '请选择参观日期', trigger: 'change' }
  ],
  visitTime: [
    { required: true, message: '请选择参观时间', trigger: 'change' }
  ],
  visitorCount: [
    { required: true, message: '请输入参观人数', trigger: 'blur' }
  ],
  researchPurpose: [
    { required: true, message: '请选择研究目的', trigger: 'change' }
  ],
  researchDetails: [
    { required: true, message: '请详细描述研究内容', trigger: 'blur' }
  ],
  protectedArea: [
    { required: true, message: '请选择要预约的保护区', trigger: 'change' }
  ]
} as const

// 获取保护区名称
const getProtectedAreaName = (areaCode: string): string => {
  const areaMap: Record<string, string> = {
    'erdihu': '胶南灵山岛保护区',
    'yunmen': '大公岛保护区',
    'bailang': '大泽山保护区',
    'xiashan': '崂山保护区',
    'binhai': '胶州艾山保护区',
    'mihe': '马山保护区'
  }
  return areaMap[areaCode] || areaCode
}

// 获取当前景区名称
const getCurrentAreaName = (): string => {
  return getProtectedAreaName(selectedArea.value)
}

// 方法
const goBack = (): void => {
  router.push('/')
}

// 禁用过去的日期
const disabledDate = (time: Date): boolean => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 处理保护区选择变化
const handleProtectedAreaChange = (): void => {
  if (reservationForm.protectedArea) {
    // 同步更新地图显示的区域
    selectedArea.value = reservationForm.protectedArea
    handleAreaChange()
  }
}

// 提交预约
const submitReservation = async (): Promise<void> => {
  if (!reservationFormRef.value) return

  try {
    const valid = await reservationFormRef.value.validate()
    if (!valid) return

    submitting.value = true

    // 创建预约记录
    const reservation: ReservationRecord = {
      id: Date.now().toString(),
      ...reservationForm,
      status: '待确认',
      createTime: new Date().toISOString(),
      visitDate: reservationForm.visitDate instanceof Date
        ? reservationForm.visitDate.toISOString().split('T')[0]
        : reservationForm.visitDate as string,
      protectedAreaName: getProtectedAreaName(reservationForm.protectedArea),
      userId: currentUserId.value
    }

    // 保存到localStorage
    const existingReservations: ReservationRecord[] = JSON.parse(
      localStorage.getItem('scientificReservations') || '[]'
    )
    existingReservations.push(reservation)
    localStorage.setItem('scientificReservations', JSON.stringify(existingReservations))

    ElMessage.success('预约提交成功！我们将在24小时内联系您确认详细安排。')

    // 重置表单
    resetForm()

    // 刷新预约记录
    loadReservations()

  } catch (error) {
    console.error('提交预约失败:', error)
    ElMessage.error('提交预约失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = (): void => {
  if (reservationFormRef.value) {
    reservationFormRef.value.resetFields()
  }
  Object.assign(reservationForm, {
    institution: '',
    contactPerson: '',
    phone: '',
    email: '',
    visitDate: '',
    visitTime: '',
    visitorCount: 1,
    researchPurpose: '',
    researchDetails: '',
    specialRequirements: '',
    protectedArea: ''
  })
}

// 加载预约记录
const loadReservations = (): void => {
  try {
    const reservations: ReservationRecord[] = JSON.parse(
      localStorage.getItem('scientificReservations') || '[]'
    )

    // 确保每个预约记录都有protectedAreaName
    const processedReservations = reservations.map(r => ({
      ...r,
      protectedAreaName: r.protectedAreaName || getProtectedAreaName(r.protectedArea || '')
    }))

    allReservations.value = processedReservations.sort((a: ReservationRecord, b: ReservationRecord) =>
      new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
    )

    // 普通用户只看自己的预约
    if (!isAdmin.value) {
      myReservations.value = processedReservations.filter(r => r.userId === currentUserId.value)
    } else {
      myReservations.value = processedReservations
    }
  } catch (error) {
    console.error('加载预约记录失败:', error)
    allReservations.value = []
    myReservations.value = []
  }
}

// 刷新预约记录
const refreshReservations = (): void => {
  loadReservations()
  ElMessage.success('预约记录已刷新')
}

// 查看预约详情
const viewReservationDetails = (reservation: ReservationRecord): void => {
  currentReservation.value = reservation
  showReservationDialog.value = true
}

// 取消预约（普通用户）
const cancelReservation = async (reservation: ReservationRecord): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？取消后无法恢复。',
      '确认取消',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '保留预约',
        type: 'warning'
      }
    )

    // 更新状态为已取消
    const reservations: ReservationRecord[] = JSON.parse(
      localStorage.getItem('scientificReservations') || '[]'
    )
    const updatedReservations = reservations.map((r: ReservationRecord) =>
      r.id === reservation.id ? { ...r, status: '已取消' as const } : r
    )
    localStorage.setItem('scientificReservations', JSON.stringify(updatedReservations))

    ElMessage.success('预约已取消')
    loadReservations()

  } catch (error) {
    // 用户取消了操作
    console.log('用户取消了取消预约操作')
  }
}

// 管理员确认预约
const confirmReservation = (reservation: ReservationRecord): void => {
  currentAdminAction.value = { type: 'confirm', reservation }
  adminActionTitle.value = '确认预约'
  adminActionPlaceholder.value = '请输入确认备注（可选）'
  adminActionForm.note = ''
  showAdminActionDialog.value = true
}

// 管理员拒绝预约
const rejectReservation = (reservation: ReservationRecord): void => {
  currentAdminAction.value = { type: 'reject', reservation }
  adminActionTitle.value = '拒绝预约'
  adminActionPlaceholder.value = '请输入拒绝原因'
  adminActionForm.note = ''
  showAdminActionDialog.value = true
}

// 管理员完成预约
const completeReservation = (reservation: ReservationRecord): void => {
  currentAdminAction.value = { type: 'complete', reservation }
  adminActionTitle.value = '完成预约'
  adminActionPlaceholder.value = '请输入完成备注（可选）'
  adminActionForm.note = ''
  showAdminActionDialog.value = true
}

// 执行管理员操作
const executeAdminAction = (): void => {
  const { type, reservation } = currentAdminAction.value
  if (!reservation) return

  const reservations: ReservationRecord[] = JSON.parse(
    localStorage.getItem('scientificReservations') || '[]'
  )

  let newStatus: ReservationRecord['status']
  let successMessage: string

  switch (type) {
    case 'confirm':
      newStatus = '已确认'
      successMessage = '预约已确认'
      break
    case 'reject':
      newStatus = '已拒绝'
      successMessage = '预约已拒绝'
      break
    case 'complete':
      newStatus = '已完成'
      successMessage = '预约已完成'
      break
    default:
      return
  }

  const updatedReservations = reservations.map((r: ReservationRecord) =>
    r.id === reservation.id
      ? { ...r, status: newStatus, adminNote: adminActionForm.note || undefined }
      : r
  )

  localStorage.setItem('scientificReservations', JSON.stringify(updatedReservations))

  ElMessage.success(successMessage)
  showAdminActionDialog.value = false
  loadReservations()
}

// 获取研究目的文本
const getResearchPurposeText = (purpose: string): string => {
  const purposeMap: Record<string, string> = {
    biodiversity: '生物多样性调查',
    environmental: '生态环境监测',
    botany: '植物学研究',
    zoology: '动物学研究',
    geology: '地质学研究',
    climate: '气候学研究',
    other: '其他'
  }
  return purposeMap[purpose] || purpose
}

// 获取状态标签类型
const getStatusTagType = (status: string): string => {
  const statusMap: Record<string, string> = {
    '待确认': 'warning',
    '已确认': 'success',
    '已完成': 'info',
    '已取消': 'danger',
    '已拒绝': 'danger'
  }
  return statusMap[status] || 'info'
}

// 处理区域变化
const handleAreaChange = (): void => {
  const currentAreaName = getCurrentAreaName()
  console.log('选择的研究区域:', currentAreaName)

  // 将地图中心移动到选中的景区
  if (view && areaCenters[selectedArea.value]) {
    view.goTo({
      center: areaCenters[selectedArea.value],
      zoom: 15
    })
  }
}

// 刷新地图
const refreshMap = (): void => {
  if (view && areaCenters[selectedArea.value]) {
    view.goTo({
      center: areaCenters[selectedArea.value],
      zoom: 15
    })
  }
  ElMessage.success('地图已刷新')
}

// 初始化地图
const initMap = async (): Promise<void> => {
  try {
    await nextTick()

    const mapContainer = document.getElementById('scientificMapView')
    if (!mapContainer) {
      console.error('地图容器未找到')
      return
    }

    // 创建地图实例
    const map = new Map({
    basemap: 'streets-vector',
  })
    // 创建地图视图
    view = new MapView({
      container: 'scientificMapView',
      map: map,
      center: areaCenters[selectedArea.value], // 根据当前选中的景区设置中心点
      zoom: 15,
      popup: {
        dockEnabled: true,
        dockOptions: {
          buttonEnabled: false,
          breakpoint: false,
        },
      },
    })

    // 创建保护区要素图层
    const featureLayerHe = new FeatureLayer({
      url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/hexinFeaturelayer/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: false,
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-fill',
          color: [225, 76, 66, 0.5], // 红色
          outline: {
            width: 0.5,
            color: 'white',
          },
        },
      },
    })
    const featureLayerHu = new FeatureLayer({
      url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/huanchong/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: false,
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-fill',
          color: [0, 112, 255, 0.5], // 蓝色
          outline: {
            width: 0.5,
            color: 'white',
          },
        },
      },
    })
    const featureLayerS = new FeatureLayer({
      url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/shiyan/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: false,
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-fill',
          color: [56, 168, 0, 0.5], // 绿色
          outline: {
            width: 0.5,
            color: 'white',
          },
        },
      },
    })

    // 将要素图层添加到地图
    map.add(featureLayerHe)
    map.add(featureLayerHu)
    map.add(featureLayerS)

    // 设置主要图层用于查询（使用第一个图层作为主要查询图层）
    featureLayer = featureLayerHe

    await view.when()
    console.log('科学研究地图初始化成功')

  } catch (error) {
    console.error('地图初始化失败:', error)
  }
}

// 组件挂载时初始化
onMounted((): void => {
  initMap()
  loadReservations()
})
</script>

<style scoped>
.scientific-research-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.scientific-research-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #2e7d32 0%, #4caf50 100%);
  color: white;
  border-radius: 12px;
  position: relative;
}

.header-actions {
  position: absolute;
  top: 20px;
  left: 20px;
}

.scientific-research-header h1 {
  margin: 0 0 10px 0;
  font-size: 2.5em;
  font-weight: 600;
}

.scientific-research-header p {
  margin: 0;
  font-size: 1.1em;
  opacity: 0.9;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.reservation-card,
.notice-card,
.my-reservations-card,
.map-card,
.area-selection-card,
.contact-card {
  margin-bottom: 20px;
}

.notice-list {
  margin: 0;
  padding-left: 20px;
}

.notice-list li {
  margin-bottom: 8px;
  line-height: 1.6;
  color: #606266;
}

.map-container {
  height: 300px;
  border-radius: 8px;
  overflow: hidden;
}

.area-options {
  padding: 10px 0;
}

.area-options .el-radio {
  display: block;
  margin-bottom: 10px;
}

.contact-info {
  padding: 10px 0;
}

.contact-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  color: #606266;
}

.contact-item .el-icon {
  margin-right: 8px;
  color: #2e7d32;
}

.reservation-details .el-descriptions {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scientific-research-container {
    padding: 10px;
  }

  .scientific-research-header {
    padding: 20px;
  }

  .scientific-research-header h1 {
    font-size: 2em;
  }

  .map-container {
    height: 250px;
  }
}
</style>
